/**
 * 表单编辑组件
 */
layui.define(['component', 'wangEditor', 'layer', 'notify', 'laydate', 'methods', 'util', 'uploadMore', 'form', 'tables'], function (exports) {
    var o = layui.jquery,
        d = layui.laydate,
        u = layui.util,
        f = layui.form,
        notify = layui.notify,
        methods = layui.methods,
        uploadMore = layui.uploadMore,
        wangEditor = layui.wangEditor,
        tables = layui.tables,
        columns = {},
        _reserved = {
            builderEvent: 'builder-event',
            builderForm: 'builderForm',
            builderFormSubmit: 'builderFormSubmit',
        },
        scanFormData = {};

    const linkCss = () => {
        layui.link('/static/admin/addons/builderPlus/extends/wangEditor/wangEditor.css');
        layui.link('/static/admin/addons/builderPlus/extends/uploadMore/uploadMore.css');
    }

    const method = {

    }

    const listen = {
        change: function () {
            columns.forEach((v) => {
                if (v.editCol.change) {
                    const keys = Object.keys(v.editCol.change);
                    const values = Object.values(v.editCol.change);
                    const query = (val) => {
                        let index = keys.indexOf(val ? val : o('input[lay-filter=' + v.field + ']:checked').val())
                        if (index !== -1) {
                            values.forEach((vs, i) => {
                                if (i === index) {
                                    vs.split(',').forEach((b) => {
                                        o("#builder-" + b).show()
                                    });
                                } else {
                                    vs.split(',').forEach((b) => {
                                        o("#builder-" + b).hide()
                                    });
                                }
                            })
                        }
                    }
                    query();
                    f.on('radio(' + v.field + ')', (e) => {
                        let val = e.elem.value;
                        query(val);
                    });
                }
            })
        },
        formSubmit: function () {

            f.verify({
                req: function (value, elem) {
                    if (!value) {
                        notify.error(o(elem).attr('placeholder'), 1000);
                        return true;
                    }
                },
            });

            f.on('submit(' + _reserved.builderFormSubmit + ')', function (data) {
                var just = data.form.getAttribute('data-just'),
                    url = data.form.getAttribute('action'),
                    body, fVal = f.val(_reserved.builderForm);

                Object.keys(fVal).forEach((v) => {
                    var type = o('input[name="' + v + '"]').attr('data-type');
                    if (type === 'ratio') {
                        fVal[v] = fVal[v] / 100;
                    }
                    if (o('input[name="' + v + '"]').attr('type') === 'checkbox') {
                        var news = [];
                        o('input[name="' + v + '"]:checked').each(function () {
                            news.push(o(this).val());
                        });
                        fVal[v] = news.join(',');
                    }
                })

                if (just === 'true') {

                    body = {
                        token: data.form.getAttribute('data-token'),
                        nav: data.form.getAttribute('data-nav'),
                        data: fVal,
                        justData: edit.getFormJustVal(fVal)
                    };
                } else {
                    body = fVal;
                }

                methods.load();
                methods.fetchThrottle(url, body, function (res) {
                    methods.closeLoad();
                    if (res.code === 1) {
                        var jq = parent.layui.jquery;
                        notify.success(res.msg, 700, function () {
                            parent.layui.layer.closeAll();
                            if (jq(".layui-table-page").length > 0) {
                                parent.layui.table.reload('builderTable', {
                                    page: {
                                        curr: jq(".layui-laypage-em").next().text()
                                    },
                                });
                            } else {
                                var w = window.frames.frameElement.id.includes('layui-layer-iframe');
                                w ? parent.location.reload() : location.reload();
                            }
                        })
                    } else {
                        notify.error(res.msg);
                    }
                }, function (e) {
                    notify.error('请求失败', 1000);
                });

                return false;
            });
        },
        preload: function () {

            u.on(_reserved.builderEvent, {
                photos: function (that) {
                    const data = [{src: o(that).attr("src")}];
                    parent.layui.layer.photos({photos: {"data": data, "start": 0}, anim: 5, closeBtn: 1});
                }
            });

            o('.builder-preload').each(function (i, that) {
                var mixed = o(that)[0].dataset;

                switch (mixed.format) {
                    case "year":
                    case "month":
                    case "date":
                    case "time":
                    case "datetime":
                        d.render({
                            elem: that,
                            type: mixed.format,
                            range: mixed.hasOwnProperty('range')
                        });
                        break;
                    case "editor":
                        const {createEditor, createToolbar} = wangEditor;
                        const editorConfig = {
                            placeholder: '在此处填写内容...',
                            filed: mixed.filed,
                            MENU_CONF: {},
                            onCreated(editor) {
                                const html = editor.getHtml()
                                o(".editor—" + mixed.filed).val(html === "<p><br></p>" ? "" : html)
                            },
                            onChange(editor) {
                                const html = editor.getHtml()
                                o(".editor—" + mixed.filed).val(html === "<p><br></p>" ? "" : html)
                            }
                        }
                        editorConfig.MENU_CONF['uploadImage'] = {
                            server: mixed.upload,
                            fieldName: 'file',
                            meta: {
                                type: 1,
                                editor: true
                            },
                            customInsert(res, insertFn) {
                                insertFn(res.data.url)
                            },

                        }
                        editorConfig.MENU_CONF['uploadVideo'] = {
                            // 上传视频的配置
                            server: mixed.upload,
                            maxFileSize: 50 * 1024 * 1024, // 5M
                            maxNumberOfFiles: 3,
                            allowedFileTypes: ['video/*'],
                            customInsert(res, insertFn) {
                                insertFn(res.data.url)
                            },
                        }

                        const editor = createEditor({
                            selector: '#editor-container-' + mixed.filed,
                            html: mixed.value,
                            config: editorConfig,
                            mode: 'default', // or 'simple'
                        })
                        const toolbar = createToolbar({
                            editor,
                            selector: '#toolbar-container-' + mixed.filed,
                            mode: 'default', // or 'simple'
                        })

                        break;
                    case "images":
                    case "video":

                        uploadMore.render({
                            elem: o(that),
                            maxNum: mixed.num || 1,
                            concurrencyMaxNum: 0,
                            uploadBtnStatus: 1,
                            progress: true,
                            style: {size: 80},
                            operation: {
                                'update': true,
                                'preview': true,
                                'delete': true
                            },
                            initValue: mixed.val ? mixed.val.split(',') : [],
                            parseData: function (res) {
                                return {code: res.code === 1 ? 0 : res.code, message: res.msg || '', url: res.data.url};
                            },
                            on: {
                                del: function (info, all, obj) {
                                    o(obj.container).find('.uploadMore-val').val(all.join(','));
                                },
                                success: function (info, all, obj) {
                                    o(obj.container).find('.uploadMore-val').val(all.join(','));
                                },
                                sort: function (all, obj) {
                                    o(obj.container).find('.uploadMore-val').val(all.join(','));
                                }
                            },
                            upload: {
                                drag: false,
                                field: 'file',
                                data: {
                                    type: mixed.format,
                                },
                                accept: mixed.format,
                                acceptMime: mixed.format + '/*',
                                url: mixed.url,
                                size: 20000,
                            },
                            sortable: {},
                        });
                        break;

                }
            })
        },
    }

    const edit = {
        getFormJustVal: function (fVal) {
            return edit.getFormData(false, fVal);
        },
        scanFormData: function () {
            edit.getFormData(true);
        },
        getFormData: function (scan = false, v = '') {
            var e = o('form[lay-filter="' + _reserved.builderForm + '"]');
            v = v ? v : f.val(_reserved.builderForm)
            e.find('[name]').each(function () {
                var name = o(this).attr('name');
                if (name && name !== 'file') {
                    var textVal = '', dataType = o(this).attr('data-type');
                    switch (this.tagName.toLowerCase()) {
                        case "input":
                        case "textarea":

                            textVal = v[name];
                            break;
                        case "select":
                            textVal = o('select[name="' + name + '"] option[value="' + v[name] + '"]').text();
                            break;
                        case "checkbox":
                            var checked = [];
                            o('input[name="' + name + '"]:checked').each(function () {
                                checked.push($(this).attr('title'));
                            });
                            textVal = checked.length > 0 ? checked.join(',') : '';
                            break;
                        case "radio":
                            textVal = o('input[name="' + name + '"]:checked').attr('title');
                            break;
                    }
                    if (scan) {
                        scanFormData[name] = {
                            field: name,
                            title: o(this).parents('.layui-form-item').find('.layui-form-label').text(),
                            originalVal: v[name],
                            originalTextVal: textVal,
                            val: v[name],
                            type: this.tagName.toLowerCase(),
                            textVal: textVal,
                            dataType: dataType
                        }
                    } else {
                        scanFormData[name].val = v[name];
                        scanFormData[name].textVal = textVal;
                        scanFormData[name].dataType = dataType;
                    }
                }
            });

            return scanFormData
        }
    }


    var component = layui.component({
        name: 'edit',
        config: {},
        render: function () {
            layui.methods.getEditGlobal().then(data => {
                columns = data;
                linkCss();
                notify.init();
                listen.preload();
                listen.formSubmit();
                columns ? listen.change() : '';
                tables.listen.listenSearchLinkage()
                edit.scanFormData();

                setTimeout(() => {
                    o('.layui-btn[lay-filter="builderFormSubmit"]').next().hide();
                    o('.layui-btn[lay-filter="builderFormSubmit"]').removeClass('layui-hide');
                }, 300)
            });
        },
    });

    layui.$.extend(component, {
        method: method
    });

    exports(component.CONST.MOD_NAME, component);
});